<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 生产计划管理
 *
 * @icon fa fa-calendar
 * @remark 管理生产计划，支持基于订单生成生产计划单
 */
class ProductionPlan extends Backend
{
    /**
     * ProductionPlan模型对象
     * @var \app\admin\model\scanwork\ProductionPlan
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\ProductionPlan;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['order', 'product', 'model', 'customer'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            // 添加统计信息
            $rows = [];
            foreach ($list as $item) {
                $row = $item->toArray();
                $stats = $item->getPlanStats();
                $row['completion_rate'] = $stats['completion_rate'];
                $row['remaining_quantity'] = $stats['remaining_quantity'];
                $row['allocation_count'] = $stats['allocation_count'];
                $row['actual_quantity'] = $stats['total_reported']; // 将total_reported映射为actual_quantity
                $rows[] = $row;
            }

            $result = array("total" => $list->total(), "rows" => $rows);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        // 获取订单列表（显示订单名称）
        $orders = \app\admin\model\scanwork\Order::where('status', '<>', 2)->select();
        $orderList = [];
        foreach ($orders as $order) {
            $orderList[$order->id] = $order->order_name ?: $order->order_no;
        }
        $this->view->assign('orderList', $orderList);
        
        // 获取产品列表
        $productList = \app\admin\model\scanwork\Product::where('status', 1)
            ->column('name', 'id');
        $this->view->assign('productList', $productList);
        
        // 获取客户列表
        $customerList = \app\admin\model\scanwork\Customer::where('status', 1)
            ->column('customer_name', 'id');
        $this->view->assign('customerList', $customerList);

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 生成计划编码
                if (empty($params['plan_code'])) {
                    $params['plan_code'] = $this->generatePlanCode();
                }
                
                // 生成计划名称
                if (empty($params['plan_name'])) {
                    $params['plan_name'] = $params['product_name'] . ' - ' . $params['product_model'] . ' - 生产计划';
                }
                
                // 检查计划编码是否唯一
                if (!$this->model->checkCodeUnique($params['plan_code'])) {
                    $this->error('计划编码已存在');
                }
                
                // 处理时间字段
                if (!empty($params['planned_start_time'])) {
                    $params['planned_start_time'] = strtotime($params['planned_start_time']);
                }
                if (!empty($params['planned_end_time'])) {
                    $params['planned_end_time'] = strtotime($params['planned_end_time']);
                }
                
                // 处理状态字段，确保是整数
                if (isset($params['status'])) {
                    $params['status'] = (int)$params['status'];
                }
                
                // 字段映射：planned_quantity -> total_quantity
                if (isset($params['planned_quantity'])) {
                    $params['total_quantity'] = (int)$params['planned_quantity'];
                    unset($params['planned_quantity']);
                }
                
                // 根据产品名称和型号名称获取对应的ID
                if (!empty($params['product_name']) && !empty($params['product_model'])) {
                    // 获取产品ID
                    $product = \app\admin\model\scanwork\Product::where('name', $params['product_name'])->find();
                    if ($product) {
                        $params['product_id'] = $product->id;
                    }
                    
                    // 获取型号ID
                    $model = \app\admin\model\scanwork\ProductModel::where('name', $params['product_model'])->find();
                    if ($model) {
                        $params['model_id'] = $model->id;
                    }
                }
                
                // 根据订单ID获取客户ID
                if (!empty($params['order_id'])) {
                    $order = \app\admin\model\scanwork\Order::find($params['order_id']);
                    if ($order && !empty($order->customer_name)) {
                        $customer = \app\admin\model\scanwork\Customer::where('customer_name', $order->customer_name)->find();
                        if ($customer) {
                            $params['customer_id'] = $customer->id;
                        }
                    }
                }

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    
                    $result = $this->model->allowField(true)->save($params);
                    
                    // 如果保存成功，生成默认工序顺序和关键节点
                    if ($result !== false) {
                        $this->model->save([
                            'process_sequence' => $this->model->generateDefaultProcessSequence(),
                            'key_milestones' => $this->model->generateKeyMilestones()
                        ]);
                    }
                    
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            } else {
                $this->error(__('Parameter %s can not be empty', ''));
            }
        }
        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取订单列表（显示订单名称）
        $orders = \app\admin\model\scanwork\Order::where('status', '<>', 2)->select();
        $orderList = [];
        foreach ($orders as $order) {
            $orderList[$order->id] = $order->order_name ?: $order->order_no;
        }
        $this->view->assign('orderList', $orderList);
        
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 处理时间字段
                if (!empty($params['planned_start_time'])) {
                    $params['planned_start_time'] = strtotime($params['planned_start_time']);
                }
                if (!empty($params['planned_end_time'])) {
                    $params['planned_end_time'] = strtotime($params['planned_end_time']);
                }
                if (!empty($params['actual_start_time'])) {
                    $params['actual_start_time'] = strtotime($params['actual_start_time']);
                }
                if (!empty($params['actual_end_time'])) {
                    $params['actual_end_time'] = strtotime($params['actual_end_time']);
                }
                
                // 处理状态字段，确保是整数
                if (isset($params['status'])) {
                    $params['status'] = (int)$params['status'];
                }
                
                // 字段映射：planned_quantity -> total_quantity
                if (isset($params['planned_quantity'])) {
                    $params['total_quantity'] = (int)$params['planned_quantity'];
                    unset($params['planned_quantity']);
                }
                
                $result = false;
                Db::startTrans();
                try {
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $item) {
                    // 检查是否有关联的分工分配
                    $allocationCount = \app\admin\model\scanwork\Allocation::where('order_id', $item->order_id)->count();
                    if ($allocationCount > 0) {
                        throw new Exception("生产计划【{$item->plan_name}】下还有{$allocationCount}个分工分配，请先删除相关分工");
                    }
                    
                    $count += $item->delete();
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        } else {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
    }

    /**
     * 查看详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取计划统计信息
        $stats = $row->getPlanStats();
        
        // 获取分工分配详情
        $allocations = \app\admin\model\scanwork\Allocation::with(['model.product', 'process', 'user'])
            ->where('order_id', $row->order_id)
            ->select();
        
        // 获取工序顺序
        $processSequence = $row->process_sequence;
        
        // 获取关键生产节点
        $keyMilestones = $row->key_milestones;
        
        $this->view->assign('row', $row);
        $this->view->assign('stats', $stats);
        $this->view->assign('allocations', $allocations);
        $this->view->assign('processSequence', $processSequence);
        $this->view->assign('keyMilestones', $keyMilestones);
        
        return $this->view->fetch();
    }

    /**
     * 生成计划编码
     */
    private function generatePlanCode()
    {
        $prefix = 'JH-' . date('Y') . '-';
        $lastCode = $this->model->where('plan_code', 'like', $prefix . '%')
            ->order('plan_code desc')
            ->value('plan_code');
        
        if ($lastCode) {
            $lastNumber = intval(substr($lastCode, -3));
            $newNumber = $lastNumber + 1;
        } else {
            $newNumber = 1;
        }
        
        return $prefix . str_pad($newNumber, 3, '0', STR_PAD_LEFT);
    }

    /**
     * 基于订单生成生产计划
     */
    public function generateFromOrder()
    {
        $orderId = $this->request->post('order_id');
        if (!$orderId) {
            $this->error('请选择订单');
        }
        
        $order = \app\admin\model\scanwork\Order::get($orderId);
        if (!$order) {
            $this->error('订单不存在');
        }
        
        // 检查是否已有生产计划
        $existingPlan = $this->model->where('order_id', $orderId)->find();
        if ($existingPlan) {
            $this->error('该订单已存在生产计划');
        }
        
        try {
            Db::startTrans();
            
            // 获取订单型号
            $orderModels = \app\admin\model\scanwork\OrderModel::with(['model.product'])
                ->where('order_id', $orderId)
                ->select();
            
            foreach ($orderModels as $orderModel) {
                $planData = [
                    'plan_code' => $this->generatePlanCode(),
                    'order_id' => $orderId,
                    'product_id' => $orderModel->model->product_id,
                    'model_id' => $orderModel->model_id,
                    'customer_id' => $order->customer_id,
                    'plan_name' => $order->order_no . ' - ' . $orderModel->model->product->name . ' - ' . $orderModel->model->name,
                    'product_name' => $orderModel->model->product->name,
                    'product_model' => $orderModel->model->name,
                    'total_quantity' => $orderModel->quantity,
                    'planned_start_time' => time(),
                    'planned_end_time' => $order->delivery_time ?: (time() + 7 * 86400), // 默认7天后
                    'status' => 0,
                    'createtime' => time()
                ];
                
                $plan = $this->model->create($planData);
                
                // 生成默认工序顺序和关键节点
                $plan->save([
                    'process_sequence' => $plan->generateDefaultProcessSequence(),
                    'key_milestones' => $plan->generateKeyMilestones()
                ]);
            }
            
            Db::commit();
            $this->success('生产计划生成成功');
            
        } catch (Exception $e) {
            Db::rollback();
            $this->error('生成失败：' . $e->getMessage());
        }
    }

    /**
     * 开始计划
     */
    public function start($ids = null)
    {
        if (!$ids) {
            $this->error('参数错误');
        }
        
        $plan = $this->model->get($ids);
        if (!$plan) {
            $this->error('生产计划不存在');
        }
        
        try {
            $plan->start();
            $this->success('计划已开始');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 暂停计划
     */
    public function pause($ids = null)
    {
        if (!$ids) {
            $this->error('参数错误');
        }
        
        $plan = $this->model->get($ids);
        if (!$plan) {
            $this->error('生产计划不存在');
        }
        
        try {
            $plan->pause();
            $this->success('计划已暂停');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 恢复计划
     */
    public function resume($ids = null)
    {
        if (!$ids) {
            $this->error('参数错误');
        }
        
        $plan = $this->model->get($ids);
        if (!$plan) {
            $this->error('生产计划不存在');
        }
        
        try {
            $plan->resume();
            $this->success('计划已恢复');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 完成计划
     */
    public function complete($ids = null)
    {
        if (!$ids) {
            $this->error('参数错误');
        }
        
        $plan = $this->model->get($ids);
        if (!$plan) {
            $this->error('生产计划不存在');
        }
        
        try {
            $plan->complete();
            $this->success('计划已完成');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 更新计划进度
     */
    public function updateProgress($ids = null)
    {
        if (!$ids) {
            $this->error('参数错误');
        }
        
        $plan = $this->model->get($ids);
        if (!$plan) {
            $this->error('生产计划不存在');
        }
        
        try {
            $plan->updateProgress();
            $this->success('进度更新成功');
        } catch (Exception $e) {
            $this->error('更新失败：' . $e->getMessage());
        }
    }

    /**
     * 获取计划统计信息
     */
    public function getPlanStats($ids = null)
    {
        if (!$ids) {
            $this->error('参数错误');
        }
        
        $plan = $this->model->get($ids);
        if (!$plan) {
            $this->error('生产计划不存在');
        }
        
        $stats = $plan->getPlanStats();
        $this->success('', null, $stats);
    }

    /**
     * 编辑工序顺序
     */
    public function editProcessSequence($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取所有工序
        $allProcesses = \app\admin\model\scanwork\Process::where('status', 1)->select();
        $this->view->assign('allProcesses', $allProcesses);
        
        if ($this->request->isPost()) {
            $processSequence = $this->request->post('process_sequence', []);
            
            try {
                $row->save(['process_sequence' => $processSequence]);
                $this->success('工序顺序更新成功');
            } catch (Exception $e) {
                $this->error('更新失败：' . $e->getMessage());
            }
        }
        
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    /**
     * 编辑关键生产节点
     */
    public function editKeyMilestones($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        if ($this->request->isPost()) {
            $keyMilestones = $this->request->post('key_milestones', []);
            
            try {
                $row->save(['key_milestones' => $keyMilestones]);
                $this->success('关键生产节点更新成功');
            } catch (Exception $e) {
                $this->error('更新失败：' . $e->getMessage());
            }
        }
        
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    /**
     * 根据订单获取产品和型号信息
     */
    public function getOrderProducts()
    {
        $orderId = $this->request->get('order_id');
        if (!$orderId) {
            return json(['code' => 0, 'msg' => '参数错误']);
        }

        try {
            $order = \app\admin\model\scanwork\Order::with(['orderModels.model.product'])->find($orderId);
            if (!$order) {
                return json(['code' => 0, 'msg' => '订单不存在']);
            }

            $products = [];
            foreach ($order->orderModels as $orderModel) {
                $model = $orderModel->model;
                $product = $model->product;
                
                $products[] = [
                    'product_id' => $product->id,
                    'product_name' => $product->name,
                    'model_id' => $model->id,
                    'model_name' => $model->name,
                    'quantity' => $orderModel->quantity
                ];
            }

            return json(['code' => 1, 'msg' => '获取成功', 'data' => $products]);

        } catch (Exception $e) {
            return json(['code' => 0, 'msg' => '获取订单产品信息失败：' . $e->getMessage()]);
        }
    }

    /**
     * 生产进度跟踪
     */
    public function progress()
    {
        try {
            // 获取所有生产计划的进度数据
            $plans = $this->model->with(['order'])->select();
            $progressList = [];
            $stats = [
                'total_plans' => 0,
                'completed_plans' => 0,
                'in_progress_plans' => 0,
                'overdue_plans' => 0,
                'overall_completion_rate' => 0,
                'on_time_rate' => 0
            ];

            $totalPlanned = 0;
            $totalActual = 0;
            $onTimeCount = 0;

            foreach ($plans as $plan) {
                $stats['total_plans']++;
                
                // 计算完成率
                $completionRate = $plan->planned_quantity > 0 ? 
                    round(($plan->actual_quantity / $plan->planned_quantity) * 100, 1) : 0;
                
                // 统计状态
                switch ($plan->status) {
                    case 'completed':
                        $stats['completed_plans']++;
                        break;
                    case 'in_progress':
                        $stats['in_progress_plans']++;
                        break;
                }
                
                // 检查是否延期
                if ($plan->status == 'in_progress' && $plan->planned_end_time < time()) {
                    $stats['overdue_plans']++;
                }
                
                // 检查是否按时完成
                if ($plan->status == 'completed' && $plan->actual_end_time <= $plan->planned_end_time) {
                    $onTimeCount++;
                }
                
                $totalPlanned += $plan->planned_quantity;
                $totalActual += $plan->actual_quantity;
                
                $progressList[] = [
                    'id' => $plan->id,
                    'plan_code' => $plan->plan_code,
                    'order_name' => $plan->order ? $plan->order->order_name : '',
                    'product_name' => $plan->product_name,
                    'product_model' => $plan->product_model,
                    'planned_quantity' => $plan->planned_quantity,
                    'actual_quantity' => $plan->actual_quantity,
                    'remaining_quantity' => $plan->planned_quantity - $plan->actual_quantity,
                    'completion_rate' => $completionRate,
                    'planned_start_time' => $plan->planned_start_time,
                    'planned_end_time' => $plan->planned_end_time,
                    'status' => $plan->status
                ];
            }
            
            // 计算整体完成率
            if ($totalPlanned > 0) {
                $stats['overall_completion_rate'] = round(($totalActual / $totalPlanned) * 100, 1);
            }
            
            // 计算按时完成率
            if ($stats['completed_plans'] > 0) {
                $stats['on_time_rate'] = round(($onTimeCount / $stats['completed_plans']) * 100, 1);
            }

            $this->view->assign('progressList', $progressList);
            $this->view->assign('stats', $stats);

            return $this->view->fetch();

        } catch (Exception $e) {
            $this->error('获取生产进度失败：' . $e->getMessage());
        }
    }
}
